import Flutter
import UIKit

public class SwiftFpluginPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
    
    var _methodChannel:FlutterMethodChannel!
    
    var _eventChannel:FlutterEventChannel!
    var _eventSink:FlutterEventSink!
    
    public static func register(with registrar: FlutterPluginRegistrar) {
          let channel = FlutterMethodChannel(name: "fplugin.method", binaryMessenger: registrar.messenger())
          let instance = SwiftFpluginPlugin(methodChannel: channel, registrar: registrar)
          registrar.addMethodCallDelegate(instance, channel: channel)
        }


    public init(methodChannel:FlutterMethodChannel, registrar: FlutterPluginRegistrar){
        super.init()
        
        //保存方法通道
        _methodChannel = methodChannel
        
        //创建事件通道
        _eventChannel = FlutterEventChannel(name: "fplugin.event", binaryMessenger: registrar.messenger())
        //注册事件通道的处理代理
        _eventChannel.setStreamHandler(self)
    }
    
    //FlutterStreamHandler methods
        public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
            _eventSink = events
            return nil;
        }

        public func onCancel(withArguments arguments: Any?) -> FlutterError? {
            _eventSink = nil;
            return nil;
        }
    
    //调用flutter的方法，并且打印返回的值
    func invokeFlutterMethod_toFlutter() {
        var resMap:[String : Any] = [String : Any]()
        resMap["item1"] = "ios value1"
        resMap["item2"] = "ios value2"
        
        //通过事件的方式调用原生
        self._eventSink(resMap);    //resMap是基本数据类型或对象
        
//        通过调用方法的方式调用flutter
//        if _methodChannel != nil {
//             _methodChannel.invokeMethod("fluMethod", arguments: resMap) { resObj in
//                print(resObj ?? "")
//            }
//        }
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        //接受flutter传过来的参数
        let argsMap = call.arguments
        
        if call.method == "getPlatformVersion"{
            result("iOS " + UIDevice.current.systemVersion)
        }else if call.method == "getNativeValue" {
            
            if let tmpMap:[String : Any] = argsMap as? [String : Any],
               let tmpMessage = tmpMap["message"] as? String{
                
                print("从flutter来的数据 " + tmpMessage)
                
                //这里再次调用flutter的方法
                invokeFlutterMethod_toFlutter()
                
                result("iOS " + tmpMessage)
            }
        }
        
    }
}
